package ee.tlnk.dao;

import java.sql.Date;
import java.sql.Time;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import ee.tlnk.model.OrderModel;
import ee.tlnk.model.RoomModel;

/**
 * The Class RoomDAOImpl.
 */
@Repository
public class RoomDAOImpl implements RoomDAO {

	/** The session factory. */
	@Autowired
	private SessionFactory sessionFactory;

	/* (non-Javadoc)
	 * @see ee.tlnk.dao.RoomDAO#addRoom(ee.tlnk.model.RoomModel)
	 */
	public void addRoom(RoomModel room) {
		sessionFactory.getCurrentSession().save(room);
	}

	/* (non-Javadoc)
	 * @see ee.tlnk.dao.RoomDAO#listRooms()
	 */
	@SuppressWarnings("unchecked")
	public List<RoomModel> listRooms() {

		return sessionFactory.getCurrentSession().createQuery("from RoomModel")
			.list();
	}

		
	
	/* (non-Javadoc)
	 * @see ee.tlnk.dao.RoomDAO#removeRoom(java.lang.Integer)
	 */
	public void removeRoom(Integer id) {
		RoomModel room = (RoomModel) sessionFactory.getCurrentSession().load(
				RoomModel.class, id);
		if (null != room) {
			sessionFactory.getCurrentSession().delete(room);
		}

	}

	/* (non-Javadoc)
	 * @see ee.tlnk.dao.RoomDAO#listValidatedRooms(java.sql.Date, java.sql.Time, java.sql.Time)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<RoomModel> listValidatedRooms(Date day, Time begin, Time end) {

		List<Integer>ordersId = new ArrayList<Integer>();
		List<OrderModel> closedOrders = (List<OrderModel>) sessionFactory
				.getCurrentSession()
				.createQuery("from OrderModel where date=:day and ((begin>:begin and end<:begin) or (begin>:end and end<:end) or (begin<=:begin and end>=:end)")
				.setDate("day", day)
				.setTime("begin", begin)
				.setTime("end", end)
			.list();
		for (OrderModel orderModel : closedOrders) {
			ordersId.add(orderModel.getId());
		}	
		return sessionFactory.getCurrentSession()
				.createQuery("from RoomModel where id not in (:list)")
				.setParameterList("list", ordersId)
				.list();

		
	}

}
